package com.digitalchina.lxnsy.fragment;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.activity.old.AActivity;
import com.digitalchina.lxnsy.activity.old.AboutUsActivity;
import com.digitalchina.lxnsy.activity.old.AccountExpertManagementActivity;
import com.digitalchina.lxnsy.activity.old.AccountPersonManagementActivity;
import com.digitalchina.lxnsy.activity.old.AuditStateActivity;
import com.digitalchina.lxnsy.activity.old.HelpAndFeedbackActivity;
import com.digitalchina.lxnsy.activity.old.LoginGuideActivity;
import com.digitalchina.lxnsy.activity.old.MyAnswerActivity;
import com.digitalchina.lxnsy.activity.old.MyAttentionActivity;
import com.digitalchina.lxnsy.activity.old.MyEnterpriseActivity;
import com.digitalchina.lxnsy.activity.old.MyFarmListActivity;
import com.digitalchina.lxnsy.activity.old.MyFarmMoneyActivity;
import com.digitalchina.lxnsy.activity.old.MyOrderListActivity;
import com.digitalchina.lxnsy.activity.old.MyQuestionActivity;
import com.digitalchina.lxnsy.activity.old.MySignInActivity;
import com.digitalchina.lxnsy.activity.old.OneKeyWifiActivity;
import com.digitalchina.lxnsy.activity.old.PersonnelServiceListActivity;
import com.digitalchina.lxnsy.activity.old.SiteTrainWaitEvaluateActivity;
import com.digitalchina.lxnsy.api.BusinessAccount;
import com.digitalchina.lxnsy.base.BaseV4Fragment;
import com.digitalchina.lxnsy.constant.Constant;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.ExpertInfoVO;
import com.digitalchina.lxnsy.entity.PersonalInfoVO;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.FrescoUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.xml.ExpertInfoXML;
import com.digitalchina.lxnsy.xml.PersonalInfoXML;
import com.digitalchina.lxnsy.xml.UserXML;
import com.facebook.drawee.view.SimpleDraweeView;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.fragment
 * 创建人：郑皓
 * 创建时间：2017/1/20 17:16
 * 修改备注：
 * ================================================
 */
public class MainPersonalFragment extends BaseV4Fragment implements Handler.Callback {

    @Bind(R.id.personal_info_sdv_header)
    SimpleDraweeView personalInfoSdvHeader;
    @Bind(R.id.personal_info_tv_name)
    TextView personalInfoTvName;
    @Bind(R.id.personal_info_iv_sex)
    ImageView personalInfoIvSex;
    @Bind(R.id.personal_info_tv_nick)
    TextView personalInfoTvNick;
    @Bind(R.id.personal_info_tv_tip)
    TextView personalInfoTvTip;
    @Bind(R.id.personal_info_tv_login)
    TextView personalInfoTvLogin;
    @Bind(R.id.personal_info_ll_account_manager)
    LinearLayout personalInfoLlAccountManager;
    @Bind(R.id.personal_info_ll_audit)
    LinearLayout personalInfoLlAudit;  // 审核状态

    private static final int LOGIN_CODE = 1;
    private static final int ACCOUNT_MANAGER_CODE = 2;
    private static final int MSG_ACTION_CALLBACK = 3;


    @Override
    public View setRootView() {
        return inflate(R.layout.fragment_main_personal_information);
    }

    @Override
    public void initMember() {

//        showActionBar();
//        setTitle("我的");

        showByLogin();
        showTipNum();

    }

    /**
     * 根据通知消息显示提示
     */
    private void showTipNum() {
        // 设置提示信息数
//            personalInfoTvTip.setVisibility(View.VISIBLE);
//            personalInfoTvTip.setText("1");
    }

    private void showByLogin() {


        if ("1".equals(UserXML.getLoginStatus(getActivity()))) {

            // 设置名称
            if (UserXML.getUserType(getActivity()).equals(Constant.USER_TYPE_EXPERT))
                personalInfoTvName.setText(ExpertInfoXML.getExpertName(getActivity()));
            else
                personalInfoTvName.setText(StringUtil.isStrEmpty(PersonalInfoXML.getTrueName(getActivity())) ? UserXML.getUseraccName(getActivity()) : PersonalInfoXML.getTrueName(getActivity()));

            // 第二行数据
            personalInfoTvNick.setText("邀请码：" + UserXML.getInviteCode(getActivity()));

            personalInfoTvName.setVisibility(View.VISIBLE);
            personalInfoTvNick.setVisibility(View.VISIBLE);
            personalInfoTvLogin.setVisibility(View.GONE);
            personalInfoIvSex.setVisibility(View.VISIBLE);
            // 显示账户管理
            personalInfoLlAccountManager.setVisibility(View.VISIBLE);
            // 设置头像
            String imagePath = PersonalInfoXML.getHeadportrait(getActivity());
            if (!TextUtils.isEmpty(imagePath)) {
                FrescoUtil.showImageSmall(imagePath, personalInfoSdvHeader);
            }

            // 设置性别
            if ("1".equals(PersonalInfoXML.getUserSex(getActivity()))) {
                personalInfoIvSex.setVisibility(View.VISIBLE);
                personalInfoIvSex.setImageResource(R.drawable.icon_sex_male);
            } else if ("0".equals(PersonalInfoXML.getUserSex(getActivity()))) {
                personalInfoIvSex.setImageResource(R.drawable.icon_sex_female);
                personalInfoIvSex.setVisibility(View.VISIBLE);
            } else {
                personalInfoIvSex.setVisibility(View.GONE);
            }

            if (UserXML.getUserType(getActivity()).equals(Constant.USER_TYPE_EXPERT)) {
                personalInfoLlAudit.setVisibility(View.VISIBLE);
                // 获取专家信息
                BusinessAccount.toEditPersonalInfo(getActivity(), mHandler);
            } else {
                personalInfoLlAudit.setVisibility(View.GONE);
                // 获取个人信息
                BusinessAccount.getPersonalInfoById(getActivity(), mHandler);
            }
        } else {
            personalInfoTvName.setVisibility(View.GONE);
            personalInfoLlAudit.setVisibility(View.GONE);
            personalInfoTvNick.setVisibility(View.GONE);
            personalInfoIvSex.setVisibility(View.GONE);
            personalInfoTvLogin.setVisibility(View.VISIBLE);
            personalInfoLlAccountManager.setVisibility(View.GONE);
            personalInfoSdvHeader.setImageResource(R.drawable.bg_default_head);
        }
    }

    @Override
    public void setHandler() {

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (getActivity() == null)
                    return;

                switch (msg.what) {
                    case MSG.MSG_GET_PERSONAL_INFO_BY_ID_SUCCESS: // 获取个人信息
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GET_PERSONAL_INFO_BY_ID_FIELD:
                        LogUtils.e(msg.obj);
                        break;
                    case MSG.MSG_TO_EDIT_PERSONAL_INFO_SUCCESS: // 专家信息
                        saveExpertInfo(msg.obj.toString());
                        break;
                    case MSG.MSG_TO_EDIT_PERSONAL_INFO_FIELD:
                        LogUtils.e(msg.obj);
                        break;
                    case MSG.MSG_APP_SHARE_SUCCESS: // app分享
                        LogUtils.e(msg.obj);
                        break;
                }
            }
        };

    }

    /**
     * 保存专家信息
     */
    private void saveExpertInfo(String json) {
        ExpertInfoVO expertInfoVO = FastJsonUtil.getBean(json, "expertInfo", ExpertInfoVO.class);

        if (expertInfoVO != null) {
            if (!StringUtil.isStrEmpty(expertInfoVO.getPhoto()))
                // 设置头像
                FrescoUtil.showImageSmall(expertInfoVO.getPhoto(), personalInfoSdvHeader);


            // 设置名称
            personalInfoTvName.setText(expertInfoVO.getExpertName());
            // 设置性别
            if ("男".equals(expertInfoVO.getExpertSex())) {
                personalInfoIvSex.setVisibility(View.VISIBLE);
                personalInfoIvSex.setImageResource(R.drawable.icon_sex_male);
                PersonalInfoXML.setUserSex(getActivity(), "1");
            } else if ("女".equals(expertInfoVO.getExpertSex())) {
                personalInfoIvSex.setVisibility(View.VISIBLE);
                personalInfoIvSex.setImageResource(R.drawable.icon_sex_female);
                PersonalInfoXML.setUserSex(getActivity(), "0");
            } else {
                personalInfoIvSex.setVisibility(View.GONE);
            }

            ExpertInfoXML.setExpertInfoVO(getActivity(), expertInfoVO);
        }
    }

    @Override
    public void callBack(Object object) {

        try {
            // 储存兴趣爱好ALL JSON 到XML
            String body = new JSONObject(object.toString()).getString("body");
            String hobby = new JSONObject(body).getString("allHobby");
            PersonalInfoXML.setAllHobbiesJson(getActivity(), hobby);
            // 储存个人信息
            savePersonalInfo(object.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    /**
     * 储存个人信息到xml
     *
     * @param json
     */
    private void savePersonalInfo(String json) {

        // 个人信息
        PersonalInfoVO personalInfoVO = FastJsonUtil.getBean(json, "body", "personalInfo", PersonalInfoVO.class);
        if (personalInfoVO != null) {
            PersonalInfoXML.setPersonalInfoVO(getActivity(), personalInfoVO);

            // 设置头像
            FrescoUtil.showImageSmall(personalInfoVO.getHeadPortrait(), personalInfoSdvHeader);
            // 设置名称
            if (UserXML.getUserType(getActivity()).equals(Constant.USER_TYPE_EXPERT))
                personalInfoTvName.setText(ExpertInfoXML.getExpertName(getActivity()));
            else
                personalInfoTvName.setText(StringUtil.isStrEmpty(PersonalInfoXML.getTrueName(getActivity())) ? UserXML.getUseraccName(getActivity()) : PersonalInfoXML.getTrueName(getActivity()));
            // 设置性别
            if ("1".equals(personalInfoVO.getUserSex())) {
                personalInfoIvSex.setImageResource(R.drawable.icon_sex_male);
            } else {
                personalInfoIvSex.setImageResource(R.drawable.icon_sex_female);
            }
        }
    }

    @OnClick({R.id.personal_info_rl_my_order, R.id.personal_info_rl_sign, R.id.personal_info_rl_attention, R.id.personal_info_rl_questions, R.id.personal_info_rl_answer, R.id.personal_info_rl_about, R.id.personal_info_rl_comment,
            R.id.personal_info_ll_account_manager, R.id.personal_info_tv_login, R.id.personal_info_rl_share, R.id.personal_info_rl_my_nb, R.id.personal_info_ll_audit, R.id.personal_info_rl_talents_info, R.id.personal_info_rl_wifi,
            R.id.personal_info_rl_my_farm,R.id.personal_info_rl_enterprise,R.id.personal_info_rl_help,R.id.rl_test})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_test: // 测试
                noLoginToSkip(AActivity.class);
                break;
            case R.id.personal_info_rl_my_order: // 我的订单
                noLoginToSkip(MyOrderListActivity.class);
                break;
            case R.id.personal_info_rl_sign:
                noLoginToSkip(MySignInActivity.class);
                break;
            case R.id.personal_info_rl_comment:
                noLoginToSkip(SiteTrainWaitEvaluateActivity.class);
                break;
            case R.id.personal_info_rl_attention:
                noLoginToSkip(MyAttentionActivity.class);
                break;
            case R.id.personal_info_rl_questions:
                noLoginToSkip(MyQuestionActivity.class);
                break;
            case R.id.personal_info_rl_answer:
                noLoginToSkip(MyAnswerActivity.class);
                break;
            case R.id.personal_info_rl_about:
                GotoUtil.gotoActivity(getActivity(), AboutUsActivity.class);
                break;
            case R.id.personal_info_ll_account_manager:
                if (UserXML.getUserType(getActivity()).equals(Constant.USER_TYPE_EXPERT))
                    startActivityForResult(new Intent(getActivity(), AccountExpertManagementActivity.class), ACCOUNT_MANAGER_CODE);
                else
                    startActivityForResult(new Intent(getActivity(), AccountPersonManagementActivity.class), ACCOUNT_MANAGER_CODE);
                break;
            case R.id.personal_info_tv_login:
                startActivityForResult(new Intent(getActivity(), LoginGuideActivity.class), LOGIN_CODE);
                break;
            case R.id.personal_info_ll_audit: // 审核状态
                startActivityForResult(new Intent(getActivity(), AuditStateActivity.class), LOGIN_CODE);
                break;
            case R.id.personal_info_rl_share: // 分享
//                showShareDialog();// 自定义分享弹出框
                break;
            case R.id.personal_info_rl_my_nb: // 我的农币
                if (Utils.isLogin(getActivity()))
                    GotoUtil.gotoActivity(getActivity(), MyFarmMoneyActivity.class);
                else
                    Utils.notLoginGoto(getActivity());
                break;
            case R.id.personal_info_rl_talents_info: // 我的人才信息
                if (!Utils.isLogin(getActivity()))
                    Utils.notLoginGoto(getActivity());
                else {
                    GotoUtil.gotoActivity(getActivity(), PersonnelServiceListActivity.class, "key", "mytalents");
                }
                break;
            case R.id.personal_info_rl_wifi: // 一键连接wifi
                if (!Utils.isLogin(getActivity()))
                    Utils.notLoginGoto(getActivity());
                else {
                    GotoUtil.gotoActivity(getActivity(), OneKeyWifiActivity.class);
                }
                break;
            case R.id.personal_info_rl_my_farm: // 我的农场
                if (!Utils.isLogin(getActivity()))
                    Utils.notLoginGoto(getActivity());
                else {
                    GotoUtil.gotoActivity(getActivity(), MyFarmListActivity.class);
                }
                break;
            case R.id.personal_info_rl_enterprise: // 我的农场
                if (!Utils.isLogin(getActivity()))
                    Utils.notLoginGoto(getActivity());
                else {
                    GotoUtil.gotoActivity(getActivity(), MyEnterpriseActivity.class);
                }
                break;
            case R.id.personal_info_rl_help: // 帮助与反馈
//                if (!Utils.isLogin(getActivity()))
//                    Utils.notLoginGoto(getActivity());
//                else {
                    GotoUtil.gotoActivity(getActivity(), HelpAndFeedbackActivity.class);
//                }
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == LOGIN_CODE || requestCode == ACCOUNT_MANAGER_CODE) {
//            if (data != null && data.hasExtra("pointVOList")) {
//                List<PointVO> pointVOList = (List<PointVO>) data.getSerializableExtra("pointVOList");
//                if (pointVOList != null && pointVOList.size() > 0) {
//                    for (int i = 0; i < pointVOList.size(); i++) {
//                        final Dialog dialog = new Dialog(getActivity(), R.style.NoBackGroundDialog);
//                        View v = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_nb, null);
//                        TextView tvNumber = (TextView) v.findViewById(R.id.dialog_tv_nb_number);
//                        TextView tvInfo = (TextView) v.findViewById(R.id.dialog_tv_nb_info);
//                        TextView tvFinish = (TextView) v.findViewById(R.id.dialog_tv_nb_finish);
//                        tvNumber.setText(MessageFormat.format("农币+{0}", pointVOList.get(i).getPointValue()));
//                        tvInfo.setText(pointVOList.get(i).getRemark());
//                        tvFinish.setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                dialog.dismiss();
//                            }
//                        });
//                        dialog.setCancelable(false);
//                        dialog.setContentView(v);
//                        dialog.show();
//                    }
//
//                }
//            }
//        }
    }

    @Override
    public void onResume() {
        super.onResume();
        showByLogin();
    }

    @Override
    public void addListener() {

    }

    @Override
    public void rightOnClick() {

    }

    @Override
    public boolean handleMessage(Message msg) {
        if (msg.what == MSG_ACTION_CALLBACK) {
            switch (msg.arg1) {
                case 1: { // 成功提示, successful notification
                    showToast(getString(R.string.ssdk_oks_share_completed));
                    LogUtils.e("------------------分享成功------------------");
                }
                break;
                case 2: { // 失败提示, fail notification
                    String expName = msg.obj.getClass().getSimpleName();
                    if ("WechatClientNotExistException".equals(expName)
                            || "WechatTimelineNotSupportedException".equals(expName)) {
                        showToast(getString(R.string.wechat_client_inavailable));
                    } else if ("GooglePlusClientNotExistException".equals(expName)) {
                        showToast(getString(R.string.google_plus_client_inavailable));
                    } else if ("QQClientNotExistException".equals(expName)) {
                        showToast(getString(R.string.qq_client_inavailable));
                    } else {
                        showToast(getString(R.string.ssdk_oks_share_failed));
                        LogUtils.e("------------------分享失败------------------");
                    }
                }
                break;
                case 3: { // 取消提示, cancel notification
                    showToast(getString(R.string.ssdk_oks_share_canceled));
                    LogUtils.e("------------------取消分享------------------");
                }
                break;
            }
        }
        return false;
    }


}